package xdu.lz.stage2_design_pattern.chapter3_observer_pattern.observerApp3;


/**
 * 主题：功能是 监视线程的生命周期状态
 */
public abstract class ObserverRunnable implements Runnable {

    //维护着观察者接口，类似订阅集合。只不过这里是单个观察者实现
    final protected ThreadLifeCycleListener listener;

    //把实现添加到 订阅集合中
    public ObserverRunnable(ThreadLifeCycleListener listener) {
        this.listener = listener;
    }

    //如果状态变化，调用所有观察者的 onEvent方法
    protected void notifyChange(RunnableEvent event){
        listener.onEvent(event);
    }

    /****************** 下面是线程的一些基本状态的定义，维护在主题内部  *******************/
    //线程状态枚举
    public enum RunnableState{
        RUNNING,ERROR,DONE;
    }

    //静态内部类，定义一些线程的状态
    public static class RunnableEvent{
        //线程状态
        private final RunnableState state;
        //多个线程
        private final Thread thread;
        //记录一些异常
        private final Throwable cause;

        public RunnableEvent(RunnableState state, Thread thread, Throwable cause) {
            this.state = state;
            this.thread = thread;
            this.cause = cause;
        }

        public RunnableState getState() {
            return state;
        }

        public Thread getThread() {
            return thread;
        }

        public Throwable getCause() {
            return cause;
        }
    }
}
